# -*- coding;utf-8 -*-
"""
File name : BaiduOcr.py.PY
Program IDE : PyCharm
Create file time: 2024/3/12 20:44
File Create By Author : 朱清闯
"""
import requests
import base64
from django.core.cache import cache


# 获取access_token
def get_baidu_ocr_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&" \
          "client_id=SwFcHUnkWD7nDXgao4VApo9P&client_secret=jK7cmgy7Pjdzq7cU03kGCn6ytL8pjT8C"
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    str_data = response.content.decode('utf-8')
    dict_data = eval(str_data)
    access_token = dict_data['access_token']
    expires_in = dict_data['expires_in']
    cache.set('ocr_access-token', access_token, expires_in)
    print(access_token)
    return access_token


# 试卷分析与识别
def get_baidu_ocr_result(file, access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/doc_analysis"
    # 二进制方式打开图片文件
    f = open(file, 'rb')
    img = base64.b64encode(f.read())
    params = {"image": img, "language_type": "CHN_ENG", "result_type": "big"}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    str_data = response.content.decode('utf-8')
    dict_data = eval(str_data)
    results_list = dict_data['results']
    print(results_list)
    ocr_result = ''
    for item in results_list:
        word = item['words']['word']
        if word != '':
            ocr_result += word
    return ocr_result
